package com.smcdd.cdb.dbo.cdb_dbo.ui.activity;


import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.zxing.pdf417.decoder.PDF417ScanningDecoder;
import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.event.SaoMiao;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.StoreList;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.DataManager;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.presenter.MainPresenter;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IMainAc;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.BitmapUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainUdis;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.GlideCircleTransform;
import com.smcdd.cdb.dbo.cdb_dbo.zhhzxing.activity.CodeUtils;
import com.smcdd.cdb.dbo.cdb_dbo.zhhzxing.decoding.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class MainActivity extends BaseActivity<IMainAc, MainPresenter> implements IMainAc {
    private TextView main_cut_user, main_username, yet_lay, not_lay, wh_lay, yet_install, for_repair, for_dispose, for_inform, mian_title, mian_title_name, main_user;
    private TextView wifi_lx_num, main_mima_num, main_line_zong, main_line_lx, main_line_zx, main_line_mm,main_line_paper,main_mima_paper;
    private ImageView mian_icon, main_image, mian_title_icon, tuichu;
    private GridView mian_gridview;
    private View mian_image_left;
    private LinearLayout image_bg_image, yet_ll, not_ll, wh_ll, page, main_wifi_zx, main_wifi_lx, main_wifi_mima, main_fang, main_line, ll_zong, ll_zx, ll_lx, ll_mm,main_wifi_paper,ll_paper;
    private boolean flag = false;
    private static final int PHOTO_CODE = 234;
    private static final int CUT_USER = 4;
    private static final int REQUEST_CODE = 5;
    private static final int SAO_CODE = 6;
    private static final int WITHDRAW = 7;
    private static final int HARDWARE_FAULT = 8;
    private static final int GREEN_LIGHTING = 9;
    private static final int UPDATE_CDB = 10;
    private static final int GET_FIRMWARE = 11;
    private static final int SEND_FACTORY = 12;
    private static final int PAPER_BH = 13;
    private AppBarLayout mAppBarLayout = null;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 3;// 从相册中选择
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private View mToolbar1 = null;
    private View mToolbar2 = null;
    private RecyclerView myRecyclerView;
    private CompositeSubscription mCompositeSubscription;
    private DataManager manager;
    private String versionCode;
    private String user;
    private String tel;
    private String eid;
    public boolean sao = true;
    private String new_eid;
    private String photo_path;

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        eid = App.SP.getString("id", "");
        String oid = App.SP.getString("oid", "");
        if (oid.equals("") || oid == null) {
            App.EDIT.putString("tel", "");
            App.EDIT.putString("id", "");
            App.EDIT.commit();
            jumpToActivity(LoginActivity.class);
            finish();
        }
        //自己的eid 3
//        App.EDIT.putString("id", "190");
//        App.EDIT.putString("id", "3");
//        App.EDIT.putString("id", "20");
//        App.EDIT.commit();
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        collapsingToolbarLayout.setStatusBarScrimColor(getResources().getColor(R.color.title_bg));
        mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
        mToolbar1 = (View) findViewById(R.id.toolbar1);
        mToolbar2 = (View) findViewById(R.id.toolbar2);
        mian_title = (TextView) findViewById(R.id.mian_title);
        page = (LinearLayout) findViewById(R.id.page);
        mian_title_name = (TextView) findViewById(R.id.mian_title_name);
        mian_title_icon = (ImageView) findViewById(R.id.mian_title_icon);
        tuichu = (ImageView) findViewById(R.id.tuichu);

        myRecyclerView = (RecyclerView) findViewById(R.id.myRecyclerView);
        GridLayoutManager mgr = new GridLayoutManager(this, 3);
        myRecyclerView.setLayoutManager(mgr);

        main_username = (TextView) findViewById(R.id.main_username);
        main_cut_user = (TextView) findViewById(R.id.main_cut_user);
        yet_lay = (TextView) findViewById(R.id.yet_lay);
        not_lay = (TextView) findViewById(R.id.not_lay);
        wh_lay = (TextView) findViewById(R.id.wh_lay);
        main_line_zong = (TextView) findViewById(R.id.main_line_zong);
        main_line_zx = (TextView) findViewById(R.id.main_line_zx);
        main_line_lx = (TextView) findViewById(R.id.main_line_lx);
        main_line_mm = (TextView) findViewById(R.id.main_line_mm);
        for_inform = (TextView) findViewById(R.id.for_inform);
        yet_install = (TextView) findViewById(R.id.yet_install);
        for_repair = (TextView) findViewById(R.id.for_repair);
        main_user = (TextView) findViewById(R.id.main_user);
        wifi_lx_num = (TextView) findViewById(R.id.wifi_lx_num);
        for_dispose = (TextView) findViewById(R.id.for_dispose);
        main_mima_num = (TextView) findViewById(R.id.main_mima_num);
        main_mima_paper = (TextView) findViewById(R.id.main_mima_paper);
        main_line_paper = (TextView) findViewById(R.id.main_line_paper);
        mian_gridview = (GridView) findViewById(R.id.mian_gridview);
        main_image = (ImageView) findViewById(R.id.main_image);
        mian_icon = (ImageView) findViewById(R.id.mian_icon);
        image_bg_image = (LinearLayout) findViewById(R.id.image_bg_image);
        yet_ll = (LinearLayout) findViewById(R.id.yet_ll);
        not_ll = (LinearLayout) findViewById(R.id.not_ll);
        wh_ll = (LinearLayout) findViewById(R.id.wh_ll);
        main_wifi_zx = (LinearLayout) findViewById(R.id.main_wifi_zx);
        main_wifi_lx = (LinearLayout) findViewById(R.id.main_wifi_lx);
        main_wifi_mima = (LinearLayout) findViewById(R.id.main_wifi_mima);
        main_wifi_paper = (LinearLayout) findViewById(R.id.main_wifi_paper);
        main_fang = (LinearLayout) findViewById(R.id.main_fang);
        main_line = (LinearLayout) findViewById(R.id.main_line);
        ll_mm = (LinearLayout) findViewById(R.id.ll_mm);
        ll_zong = (LinearLayout) findViewById(R.id.ll_zong);
        ll_zx = (LinearLayout) findViewById(R.id.ll_zx);
        ll_lx = (LinearLayout) findViewById(R.id.ll_lx);
        ll_paper = (LinearLayout) findViewById(R.id.ll_paper);
        mian_image_left = findViewById(R.id.mian_image_left);

        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {
                    //张开
                    mToolbar1.setVisibility(View.VISIBLE);
                    mToolbar2.setVisibility(View.GONE);
                    setToolbar1Alpha(255);
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    //收缩
                    mToolbar1.setVisibility(View.GONE);
                    mToolbar2.setVisibility(View.VISIBLE);
                    setToolbar2Alpha(255);
                } else {
                    int alpha = 255 - Math.abs(verticalOffset);
                    if (alpha < 0) {
                        Log.e("alpha", alpha + "");
                        //收缩toolbar
                        mToolbar1.setVisibility(View.GONE);
                        mToolbar2.setVisibility(View.VISIBLE);
                        setToolbar2Alpha(Math.abs(verticalOffset));
                    } else {
                        //张开toolbar
                        mToolbar1.setVisibility(View.VISIBLE);
                        mToolbar2.setVisibility(View.GONE);
                        setToolbar1Alpha(alpha);
                    }
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        loadData();
    }

    @Override
    public void initData() {

        String url = App.SP.getString("url", "");
        user = App.SP.getString("user", "");
        tel = App.SP.getString("tel", "");
        if (!url.equals("")) {
            RequestOptions myOptions = new RequestOptions()
                    .transform(new GlideCircleTransform(MainActivity.this));
            Glide.with(MainActivity.this)
                    .load(url)
                    .apply(myOptions)
                    .into(mian_icon);
            Glide.with(MainActivity.this)
                    .load(url)
                    .apply(myOptions)
                    .into(mian_title_icon);
        }
        main_username.setText(tel);
        main_user.setText(user);
        mian_title_name.setText(user);
        String udid = ObtainUdis.getUDID(MainActivity.class);
        App.EDIT.putString("udid", udid);
        App.EDIT.commit();
        mPresenter.loadContacts(udid);
    }

    @Override
    public void initListener() {
        //wifi在线
        main_wifi_zx.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PageActivity.class);
            intent.putExtra("status", "1");
            startActivity(intent);
        });
        ll_zx.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PageActivity.class);
            intent.putExtra("status", "1");
            startActivity(intent);
        });

        //wifi离线
        main_wifi_lx.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PageActivity.class);
            intent.putExtra("status", "2");
            startActivity(intent);
        });
        ll_lx.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PageActivity.class);
            intent.putExtra("status", "2");
            startActivity(intent);
        });
        //密码设备
        main_wifi_mima.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PageActivity.class);
            intent.putExtra("status", "3");
            startActivity(intent);
        });
        ll_mm.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PageActivity.class);
            intent.putExtra("status", "3");
            startActivity(intent);
        });
        //纸巾机设备
        ll_paper.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PageActivity.class);
            intent.putExtra("status", "4");
            startActivity(intent);
        });
        main_wifi_paper.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PageActivity.class);
            intent.putExtra("status", "4");
            startActivity(intent);
        });
        //退出
        tuichu.setOnClickListener(v -> {
            App.EDIT.putString("tel", "");
            App.EDIT.putString("id", "");
            App.EDIT.commit();
            jumpToActivity(LoginActivity.class);
            finish();
        });
        //待维护
        wh_ll.setOnClickListener(v -> {
            jumpToActivity(MaintainActivity.class);
        });
        //已安装
        page.setOnClickListener(v -> jumpToActivity(PageActivity.class));
        ll_zong.setOnClickListener(v -> jumpToActivity(PageActivity.class));
        //已铺设
        yet_ll.setOnClickListener(v -> {
            jumpToActivity(MenDianActivity.class);
        });
        //待铺设
        not_ll.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, MenDianActivity.class);
            intent.putExtra("not", "not");
            startActivity(intent);
        });
        //右下角小图标点击事件
        main_image.setOnClickListener(v -> {
            if (flag) {
                image_bg_image.setVisibility(View.GONE);
            } else {
                image_bg_image.setVisibility(View.VISIBLE);
            }
            flag = !flag;
        });
        //小图标展开左边小房子点击事件
        mian_image_left.setOnClickListener(v -> jumpToActivity(AddMenDianActivity.class));
        mian_icon.setOnClickListener(v -> mPresenter.selectImgs());
    }

    //首页数据
    public void loadData() {
        mCompositeSubscription = new CompositeSubscription();
        manager = new DataManager(this);
        versionCode = ObtainVersion.getVersionName(this);
        String time = System.currentTimeMillis() + "";
        String udid = ObtainUdis.getUDID(MainActivity.class);
        String id = App.SP.getString("id", "");
        String encry = ObtainEncry.getStatistics("2", time, versionCode, NetWorkCodeInfo.STATISTICS, udid, id);
        mCompositeSubscription.add(manager.getStatistics("2", time, versionCode, NetWorkCodeInfo.STATISTICS, udid, id, encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<StoreList>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(StoreList storeList) {
                        Log.e("MainPresenter", storeList.getCode() + "");
                        if (storeList.getCode() == 200) {
                            wh_lay.setText(storeList.getData().getMaintenance_num());
                            yet_lay.setText(storeList.getData().getAlready_pushe());
                            not_lay.setText(storeList.getData().getStay_pushe());
                            yet_install.setText(storeList.getData().getAlready_anzhuang());
                            main_line_zong.setText(storeList.getData().getAlready_anzhuang());
                            main_line_paper.setText(storeList.getData().getPaper_num()+"");


                            main_mima_paper.setText(storeList.getData().getPaper_num()+"");
                            for_inform.setText(storeList.getData().getOnline_num());
                            main_line_zx.setText(storeList.getData().getOnline_num());

                            wifi_lx_num.setText(storeList.getData().getOffline_num());
                            main_line_lx.setText(storeList.getData().getOffline_num());

                            main_mima_num.setText(storeList.getData().getMima_num());
                            main_line_mm.setText(storeList.getData().getMima_num());
                            for_repair.setText(storeList.getData().getAlready_withdrawn());
                            for_dispose.setText(storeList.getData().getAlready_fault());
                        }
                    }
                }));
    }


    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main_title;
    }

    @Override
    public RecyclerView getRecycler() {
        return myRecyclerView;
    }

    @Override
    public MainActivity getMainActivity() {
        return MainActivity.this;
    }

    @Override
    public TextView getMain_cut_user() {
        return main_cut_user;
    }

    @Override
    public LinearLayout getMain_ch() {
        return main_line;
    }

    @Override
    public LinearLayout getMain_gz() {
        return main_fang;
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE:
                //激活设备
                if (null != data) {
                    if (sao) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            getCode(data,REQUEST_CODE);
                            break;
                        }
                        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                            String result = bundle.getString(CodeUtils.RESULT_STRING);
                            int type = bundle.getInt("send_factory");
                            if (result.equals("input")) {
                                Intent intent = new Intent(MainActivity.this, InputActivity.class);
                                intent.putExtra("send_factory", type);
                                startActivity(intent);
                            } else {
                                mPresenter.dialog();
                                mPresenter.parse(result, REQUEST_CODE);
                            }
                            // ToastUtil.showToast(substring);
                        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                            ToastUtil.showToast("解析二维码失败");
                        }else{
                            getCode(data,REQUEST_CODE);
                        }

                    } else {
                        int type = data.getIntExtra("send_factory", 0);
                        String result = data.getStringExtra("result");
                        if (result.equals("input")) {
                            Intent intent = new Intent(MainActivity.this, InputActivity.class);
                            intent.putExtra("send_factory", type);
                            startActivity(intent);
                        } else {
                            mPresenter.dialog();
                            mPresenter.parse(result, REQUEST_CODE);
                        }
                    }

                }
                break;
            case PAPER_BH:
                //补货纸巾机
                if (null != data) {
                    if (sao) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            getCode(data,PAPER_BH);
                            break;
                        }
                        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                            String result = bundle.getString(CodeUtils.RESULT_STRING);
                            int type = bundle.getInt("send_factory");
                            if (result.equals("input")) {
                                Intent intent = new Intent(MainActivity.this, InputActivity.class);
                                intent.putExtra("send_factory", type);
                                startActivity(intent);
                            } else {
                                mPresenter.dialog();
                                mPresenter.parse(result, PAPER_BH);
                            }
                            // ToastUtil.showToast(substring);
                        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                            ToastUtil.showToast("解析二维码失败");
                        }else{
                            getCode(data,PAPER_BH);
                        }

                    } else {
                        int type = data.getIntExtra("send_factory", 0);
                        String result = data.getStringExtra("result");
                        if (result.equals("input")) {
                            Intent intent = new Intent(MainActivity.this, InputActivity.class);
                            intent.putExtra("send_factory", type);
                            startActivity(intent);
                        } else {
                            mPresenter.dialog();
                            mPresenter.parse(result, PAPER_BH);
                        }
                    }

                }
                break;
            case SAO_CODE:
                //扫一扫
                if (null != data) {
                    if (sao) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            getCode(data,SAO_CODE);
                            break;
                        }
                        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                            String result = bundle.getString(CodeUtils.RESULT_STRING);
                            int type = bundle.getInt("send_factory");
                            if (result.equals("input")) {
                                Intent intent = new Intent(MainActivity.this, InputActivity.class);
                                intent.putExtra("send_factory", type);
                                startActivity(intent);
                            } else {
                                mPresenter.dialog();
                                mPresenter.parse(result, SAO_CODE);
                            }
                            // ToastUtil.showToast(substring);
                        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                            ToastUtil.showToast("解析二维码失败");
                        }
                        else{
                            getCode(data,SAO_CODE);
                        }

                    } else {
                        int type = data.getIntExtra("send_factory", 0);
                        String result = data.getStringExtra("result");
                        if (result.equals("input")) {
                            Intent intent = new Intent(MainActivity.this, InputActivity.class);
                            intent.putExtra("send_factory", type);
                            startActivity(intent);
                        } else {
                            mPresenter.dialog();
                            mPresenter.parse(result, SAO_CODE);
                        }
                    }

                }

                break;
            case WITHDRAW:
                //设备撤回
                if (null != data) {
                    if (sao) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            getCode(data,WITHDRAW);
                            break;
                        }
                        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                            String result = bundle.getString(CodeUtils.RESULT_STRING);
                            int type = bundle.getInt("send_factory");
                            if (result.equals("input")) {
                                Intent intent = new Intent(MainActivity.this, InputActivity.class);
                                intent.putExtra("send_factory", type);
                                startActivity(intent);
                            } else {
                                mPresenter.parse(result, WITHDRAW);
                            }
                        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                            ToastUtil.showToast("解析二维码失败");
                        } else{
                            getCode(data,WITHDRAW);
                        }

                    } else {
                        String result = data.getStringExtra("result");
                        int type = data.getIntExtra("send_factory", 0);
                        if (result.equals("input")) {
                            Intent intent = new Intent(MainActivity.this, InputActivity.class);
                            intent.putExtra("send_factory", type);
                            startActivity(intent);
                        } else {
                            mPresenter.parse(result, WITHDRAW);
                        }
                    }

                }

                break;
            case HARDWARE_FAULT:
                //硬件故障
                if (null != data) {
                    if (sao) {
                        if (null != data) {
                            Bundle bundle = data.getExtras();
                            if (bundle == null) {
                                getCode(data,HARDWARE_FAULT);
                                break;
                            }
                            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                                String result = bundle.getString(CodeUtils.RESULT_STRING);
                                mPresenter.parse(result, HARDWARE_FAULT);
                                // ToastUtil.showToast(substring);
                            } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                                ToastUtil.showToast("解析二维码失败");
                            } else{
                                getCode(data,HARDWARE_FAULT);
                            }
                        }
                    } else {
                        String result = data.getStringExtra("result");
                        mPresenter.parse(result, HARDWARE_FAULT);
                    }

                }


                break;
            case GREEN_LIGHTING:
                //灯光控制
                if (null != data) {
                    if (sao) {
                        if (null != data) {
                            Bundle bundle = data.getExtras();
                            if (bundle == null) {
                                getCode(data,GREEN_LIGHTING);
                                break;
                            }
                            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                                String result = bundle.getString(CodeUtils.RESULT_STRING);
                                mPresenter.parse(result, GREEN_LIGHTING);
                                // ToastUtil.showToast(substring);
                            } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                                ToastUtil.showToast("解析二维码失败");
                            } else{
                                getCode(data,GREEN_LIGHTING);
                            }
                        }
                    } else {
                        String result = data.getStringExtra("result");
                        mPresenter.parse(result, GREEN_LIGHTING);
                    }

                }

                break;
            case UPDATE_CDB:
                //灯光控制
                if (null != data) {
                    if (sao) {
                        if (null != data) {
                            Bundle bundle = data.getExtras();
                            if (bundle == null) {
                                getCode(data,UPDATE_CDB);
                                break;
                            }
                            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                                String result = bundle.getString(CodeUtils.RESULT_STRING);
                                mPresenter.parse(result, UPDATE_CDB);
                                // ToastUtil.showToast(substring);
                            } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                                ToastUtil.showToast("解析二维码失败");
                            } else{
                                getCode(data,UPDATE_CDB);
                            }
                        }
                    } else {
                        String result = data.getStringExtra("result");
                        mPresenter.parse(result, UPDATE_CDB);
                    }

                }

                break;
            case GET_FIRMWARE:
                //获取最新固件
                if (null != data) {
                    if (sao) {
                        if (null != data) {
                            Bundle bundle = data.getExtras();
                            if (bundle == null) {
                                getCode(data,GET_FIRMWARE);
                                break;
                            }
                            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                                String result = bundle.getString(CodeUtils.RESULT_STRING);
                                mPresenter.parse(result, GET_FIRMWARE);
                                // ToastUtil.showToast(substring);
                            } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                                ToastUtil.showToast("解析二维码失败");
                            } else{
                                getCode(data,GET_FIRMWARE);
                            }
                        }
                    } else {
                        String result = data.getStringExtra("result");
                        mPresenter.parse(result, GET_FIRMWARE);
                    }

                }

                break;
            case SEND_FACTORY:
                //寄回工厂
                if (null != data) {
                    if (sao) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            getCode(data,SEND_FACTORY);
                            break;
                        }
                        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                            String result = bundle.getString(CodeUtils.RESULT_STRING);
                            int type = bundle.getInt("send_factory");
                            if (result.equals("input")) {
                                Intent intent = new Intent(MainActivity.this, InputActivity.class);
                                intent.putExtra("send_factory", type);
                                startActivity(intent);
                            } else {
                                mPresenter.dialog();
                                mPresenter.parse(result, SEND_FACTORY);
                            }
                            // ToastUtil.showToast(substring);
                        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                            ToastUtil.showToast("解析二维码失败");
                        }else {
                            getCode(data,SEND_FACTORY);
                        }

                    } else {
                        int type = data.getIntExtra("send_factory", 0);
                        String result = data.getStringExtra("result");
                        if (result.equals("input")) {
                            Intent intent = new Intent(MainActivity.this, InputActivity.class);
                            intent.putExtra("send_factory", type);
                            startActivity(intent);
                        } else {
                            mPresenter.dialog();
                            mPresenter.parse(result, SEND_FACTORY);
                        }
                    }

                }

                break;
            case PHOTO_REQUEST_GALLERY:
                // 从相册返回的数据
                if (data != null) {
                    // 得到图片的全路径
                    Uri uri = data.getData();

                    RequestOptions myOptions = new RequestOptions()
                            .transform(new GlideCircleTransform(MainActivity.this));
                    Glide.with(MainActivity.this)
                            .load(uri)
                            .apply(myOptions)
                            .into(mian_icon);
                    Glide.with(MainActivity.this)
                            .load(uri)
                            .apply(myOptions)
                            .into(mian_title_icon);
                    App.EDIT.putString("url", uri.toString());
                    App.EDIT.commit();
                }
                break;
            case PHOTO_REQUEST_CAREMA:
                // 从相机返回的数据
                if (hasSdcard()) {
                    Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                            PHOTO_FILE_NAME));
                    RequestOptions myOptions = new RequestOptions()
                            .transform(new GlideCircleTransform(MainActivity.this));
                    Glide.with(MainActivity.this)
                            .load(uri)
                            .apply(myOptions)
                            .into(mian_icon);
                    Glide.with(MainActivity.this)
                            .load(uri)
                            .apply(myOptions)
                            .into(mian_title_icon);
                    App.EDIT.putString("url", uri.toString());
                    App.EDIT.commit();

                } else {
                    ToastUtil.showToast("未找到存储卡，无法存储照片！");
                }
                break;
            case CUT_USER:
                //切换用户
                if (data != null) {
                    new_eid = data.getStringExtra("new_eid");
                    String new_user = data.getStringExtra("new_user");
                    String new_mobile = data.getStringExtra("new_mobile");
                    String new_admin = data.getStringExtra("new_admin");
                    if (new_eid.equals(eid)) {
                        main_username.setText(tel);
                        main_user.setText(user);
                    } else {
                        main_username.setText(tel + "(" + new_mobile + ")");
                        main_user.setText(user + "(" + new_user + ")");
                    }
                    if (new_admin.equals("1")) {
                        main_line.setVisibility(View.GONE);
                        main_fang.setVisibility(View.VISIBLE);
                    } else {
                        main_line.setVisibility(View.VISIBLE);
                        main_fang.setVisibility(View.GONE);
                    }
                    App.EDIT.putString("id", new_eid);
                    App.EDIT.commit();
                }

                break;
        }
    }

    public void getCode(Intent data,int code){
        if( data.getData() != null){
            String[] proj = { MediaStore.Images.Media.DATA };
            // 获取选中图片的路径
            Cursor cursor = getContentResolver().query(data.getData(),
                    proj, null, null, null);
            if (cursor.moveToFirst()) {
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                photo_path = cursor.getString(column_index);
                if (photo_path == null) {
                    photo_path = Utils.getPath(this,
                            data.getData());
                    Log.i("123path  Utils", photo_path);
                }
                Log.i("123path", photo_path);
            }
            cursor.close();

            Log.e("photo_path",photo_path);

            new Thread(new Runnable() {

                @Override
                public void run() {
                    CodeUtils.analyzeBitmap(photo_path, new CodeUtils.AnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mPresenter.parse(result, code);
                                    Log.e("photo",result);
                                }
                            });

                        }

                        @Override
                        public void onAnalyzeFailed() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.showToast("二维码识别错误");
                                }
                            });
                        }
                    });
                }
            }).start();
        }else {
            ToastUtil.showToast("二维码解析失败");
        }



    }


    /*
   * 判断sdcard是否被挂载
   */
    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }


    //设置展开时各控件的透明度
    public void setToolbar1Alpha(int alpha) {
        mian_title.setTextColor(Color.argb(alpha, 255, 255, 255));
    }

    //设置闭合时各控件的透明度
    public void setToolbar2Alpha(int alpha) {
        mian_title.setTextColor(Color.argb(alpha, 255, 255, 255));
        mian_title_name.setTextColor(Color.argb(alpha, 255, 255, 255));
    }

    //刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefresh(String event) {
        if (event.equals("refresh")) {
            loadData();
        } else if (event.equals("laid")) {
            loadData();
        }
    }

    //手动输入设备ID
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSaoMiao(SaoMiao event) {
        int type = event.getType();
        switch (type) {
            case WITHDRAW:
                mPresenter.NetWork(WITHDRAW, event.getAlias(),1);
                break;
            case SEND_FACTORY:
                mPresenter.NetWork(SEND_FACTORY, event.getAlias(),1);
                break;
            case SAO_CODE:
                mPresenter.NetWork(SAO_CODE, event.getAlias(),1);
                break;
            case REQUEST_CODE:
                mPresenter.NetWork(REQUEST_CODE, event.getAlias(),1);
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.unLoadData();
        String old_id = App.SP.getString("old_id", "");
        App.EDIT.putString("id", old_id);
        App.EDIT.commit();
        EventBus.getDefault().unregister(this);
    }
}
